
import UserService.User;
import UserService.UserDaoImp;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
@WebServlet(name="UsermessageServlet",value ="/UsermessageServlet")
public class UsermessageServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        HttpSession session = req.getSession(true);
        session.setMaxInactiveInterval(60 * 60);//session储存时间为1小时
        User user = (User) session.getAttribute("user");//方便获取登录之后的那个用户的用户名和密码

        String  submitButton= req.getParameter("submitButton");//提交按钮
        String returnButton=req.getParameter("returnButton");//返回按钮
        String error="  ";

        if (submitButton!=null){//用户按下修改按钮，进行信息的修改
            String username=req.getParameter("username");//用户名
            String password = req.getParameter("password");//密码
            String newpassword = req.getParameter("newpassword");//新密码
            String phone=req.getParameter("phone");//联系电话
            if (password.equals(user.getPassword())){
                UserDaoImp u=new UserDaoImp();//判断用户输入的密码是否跟原密码一致，省去判断空的步骤
                u.updateUser(user,username,newpassword,phone);
                User user1=u.finduser(user.getUname());//获取更改密码后的新用户
                session.removeAttribute("user");//移除原有session名字方便进行存储
                session.setAttribute("user",user1);//重新添加session用户
                error="  修改成功！  ";
                req.setAttribute("error", error);
                req.getRequestDispatcher("UserMessage.jsp").forward(req, resp);}
            else {//不相等直接error输出原密码错误并重新定向
                error="  原密码错误！ ";
                req.setAttribute("error", error);
                req.getRequestDispatcher("UserMessage.jsp").forward(req, resp);
            }

        }else if(returnButton!=null){//用户按下返回按钮，返回主页面
            req.getRequestDispatcher("userSite.jsp").forward(req, resp);
        }

    }
}
